package com.elf.reactnative;

import android.app.Application;
import android.text.TextUtils;

import com.elf.reactnative.nativepackage.NavigationPackage;
import com.facebook.infer.annotation.Assertions;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactInstanceManagerBuilder;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.common.LifecycleState;
import com.facebook.react.shell.MainReactPackage;
import com.microsoft.codepush.react.CodePush;
import com.reactnativecommunity.asyncstorage.AsyncStoragePackage;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Nullable;

public class ReactNativeHostImpl extends ReactNativeHost {

    private String mJsBundleFile;

    protected ReactNativeHostImpl(Application application, String jsBundleFile) {
        super(application);
        mJsBundleFile = jsBundleFile;
    }

    @Override
    protected ReactInstanceManager createReactInstanceManager() {
        ReactInstanceManagerBuilder builder = ReactInstanceManager.builder()
                .setApplication(getApplication())
                .setJSMainModulePath(getJSMainModuleName())
                .setUseDeveloperSupport(getUseDeveloperSupport())
                .setRedBoxHandler(getRedBoxHandler())
                .setJavaScriptExecutorFactory(getJavaScriptExecutorFactory())
                .setUIImplementationProvider(getUIImplementationProvider())
                .setJSIModulesPackage(getJSIModulePackage())
                .setInitialLifecycleState(LifecycleState.RESUMED);

        for (ReactPackage reactPackage : getPackages()) {
            builder.addPackage(reactPackage);
        }

        String jsBundleFile = getJSBundleFile();
        if (TextUtils.isEmpty(jsBundleFile)) {
            builder.setBundleAssetName(Assertions.assertNotNull(getBundleAssetName()));
        } else {
            builder.setJSBundleFile(jsBundleFile);
        }
        return builder.build();
    }

    @Override
    public boolean getUseDeveloperSupport() {
        return BuildConfig.DEBUG;
    }

    @Override
    protected String getJSMainModuleName() {
        return "index";
    }

    @Nullable
    @Override
    protected String getBundleAssetName() {
        return "index.bundle";
    }

    @Nullable
    @Override
    protected String getJSBundleFile() {
        return mJsBundleFile;
    }

    @Override
    protected List<ReactPackage> getPackages() {
        List<ReactPackage> list = new ArrayList<>();
        list.add(new MainReactPackage());
        list.add(new NavigationPackage());
        list.add(new CodePush("",getApplication()));
        list.add(new AsyncStoragePackage());
        return list;
    }
}